package com.shop.resource.controller;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@RestController
@CrossOrigin
public class FileUpload {
    private static String accessKey = "YBOHrX9Lcvk73pqUqVIRNybKj4eE4mwBiuQ20VOs";
    private static String secretKey = "GLO5j0STcLseat2DNI0V1-gzlzLxkZZvJjMU4yAQ";
    private static String bucket = "photo";

    /**
     *
     * @Description: 上传图片到七牛云
     *
     *
     * @return 图片的链接地址
     *
     * @version: v1.0.0
     * @author: ZLK
     * @date: 2018/6/28 14:39
     *
     * Modification History:
     * Date         Author          Version            Description
     *---------------------------------------------------------*
     * 2018/6/28      zhoulk          v1.0.0             新建
     */
    @RequestMapping(value = "/uploadImgToQn", method = RequestMethod.POST)
    public @ResponseBody
    UploadImg uploadImgToQi(MultipartHttpServletRequest request) {
        MultipartFile img= request.getFile("imgFile");
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        String key= UUID.randomUUID().toString()+".jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String name="";
        try {
            Response response =   uploadManager.put(img.getBytes(),key,upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            name=putRet.key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] values = { "http://resource.teemor.xyz/"+name };
        UploadImg imgInfo = new UploadImg();
        imgInfo.setErrno(0);
        imgInfo.setData(values);
        return imgInfo;
    }
}

class UploadImg {
    private Integer errno;
    private String[] data;

    public Integer getErrno() {
        return errno;
    }

    public void setErrno(Integer errno) {
        this.errno = errno;
    }

    public String[] getData() {
        return data;
    }

    public void setData(String[] data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ImgInfo [error=" + errno + ", url=" + Arrays.toString(data) + "]";
    }
}
